import React, { PureComponent } from 'react'
/* 在线练习 */
import { Col, Row, Card, Button, Radio, Spin, Modal, message, Checkbox } from 'antd';
import styles from './index.less';
import { stopActive } from '@/utils/utils'
import { getTestPaper, submitPracticePaper, saveWrongOrMarkedQuestions } from '@/services/studentPractice'
import { getHandle, fileurl } from '@/services/baseurl'
import { history } from 'umi'
const RadioGroup = Radio.Group;
let timer = null;
export default class Index extends PureComponent<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            data: [],
            answers: [],
            abc: 1,
            currentQuestion: 0,
            loading: true,
            submited: false,
            markedQuestions: [],
            showSaveQuestionBank: false,
            allWrongAnswers: [],//所有错题包含未答
            allIds: [],//所有题
            correctAnswers: [],//做对的没标记的题
            rightAnswers: [],//做对的
            markedSave: false,
            allSave: false,
            wrongAnswers: [],
            checkboxValues: [],
            id: '',
            startTime: 0,
            reFinish: false
        }
    }
    changeCurrentQuestion = (item: any, index: number) => () => {
        this.setState({
            abc: 1,
            currentQuestion: index
        })
        let anchorElement = document.getElementById('question' + index);
        if (anchorElement) {
            anchorElement.scrollIntoView({ block: 'start' });
        }

    }
    changeAnswer = (index: number) => () => {
        const value = event?.target.value;
        const { answers, data } = this.state;
        answers[index] = value;
        data[index].is_audit = 2;
        this.setState({
            currentQuestion: index,
            answers: [...answers],
            data: [...data]
        });
    }
    changeBatchSelect = (e: any, index: number) => {
        const { answers, data, checkboxValues } = this.state;
        answers[index] = e.sort().join(',').replace(/,/g, '');
        checkboxValues[index] = e;
        if (data[index].is_audit !== 3) {
            if (e[0]) {
                data[index].is_audit = 2;
            } else {
                data[index].is_audit = 0;
            }
        }
        this.setState({
            currentQuestion: index,
            checkboxValues: [...checkboxValues]
        })
    }
    markThisQuestion = (index: number) => () => {
        const data = this.state.data;
        data[index].is_audit = 3;
        const markedQuestions = this.state.markedQuestions;
        markedQuestions.push(data[index].id)
        this.setState({
            abc: 1
        })
        message.success('已标记')
    }

    checkAnswer = (item: any) => () => {
        Modal.info({
            title: "答案",
            content: `${item.answer} ${item.answer_that ? '(' + item.answer_that + ')' : ''}`
        })
    }

    submitHandle = () => {
        const { data, answers, markedQuestions, reFinish } = this.state;
        let allIds = [];
        let wrongAnswers = [];
        let allWrongAnswers = [];
        let correctAnswers = [];
        let rightAnswers = [];
        let wrong_done = [];//做过的错题
        let wrong_done_right = [];//答对的错题
        let complete = [];//做过的题
        for (let i = 0; i < data.length; i++) {
            if (data[i].is_audit !== 3 && data[i].wrong !== 1 && !reFinish) {
                allIds.push(data[i].id);
            }
            if (data[i].answer.trim() !== answers[i]) {
                allWrongAnswers.push(data[i].id)
            }
            if (data[i].answer.trim() !== answers[i] && answers[i]) {
                wrongAnswers.push(data[i].id)

            }
            if (answers[i]) {
                correctAnswers.push(data[i].id)
                if (data[i].wrong) {
                    wrong_done.push(data[i].id)
                }

            }
            if (answers[i] && data[i].wrong !== 1) {
                complete.push(data[i].id)
            }
            if (data[i].answer.trim() === answers[i]) {
                rightAnswers.push(data[i].id)
                if (data[i].wrong) {
                    wrong_done_right.push(data[i].id)
                }
            }
        }
        this.setState({
            allWrongAnswers,
            allIds,
            correctAnswers,
            rightAnswers,
            wrongAnswers,
            markedQuestions
        })
        const applySubmit = () => {
            const { type, subject, question_subject, question_type, question_p_type, id } = this.props.match.params;
            const uid = localStorage.getItem('id');
            const { startTime } = this.state;
            const time = startTime === 0 ? 0 : new Date().getTime() - startTime;
            submitPracticePaper({ id, wrong_done, wrong_done_right, complete, time: time >= 7200000 ? 7200000 : time, uid, right_num: rightAnswers.length, wrongAnswers: [], allIds, correctAnswers, marked: [], rightAnswers, all: data.length, type, subject, wrong_num: wrongAnswers.length }).then(res => {
                if (res.status === 1) {
                    message.success('已交卷');
                    const userinfo = JSON.parse(localStorage.getItem('userinfo') || '');
                    const operation = userinfo.name + `提交了专项练习（${question_subject},${question_type},${question_p_type}）`
                    getHandle({ operation })
                    this.setState({
                        submited: true,
                        id
                    })
                }
            })
        }
        if (answers.indexOf('') !== -1) {
            return Modal.confirm({
                title: '提示',
                content: '您还有试题未作答完成，确定交卷吗？',
                onOk: () => {
                    applySubmit()

                }
            })
        }
        Modal.confirm({
            title: '提示',
            content: '您确定要交卷吗？',
            onOk: () => {
                applySubmit()
            }
        })
    }
    showSaveQuestionBank = () => {
        this.setState({
            showSaveQuestionBank: true
        })
    }
    hideSaveQuestionBank = () => {
        this.setState({
            showSaveQuestionBank: false
        })
    }
    saveWrongOrMarkedQuestions = () => {
        const { wrongAnswers, id } = this.state;
        saveWrongOrMarkedQuestions({ wrongAnswers, id }).then(res => {
            if (res.status === 1) {
                message.success('已存储');
            }
        })
    }
    confirmSave = () => {
        this.hideSaveQuestionBank();
        this.saveWrongOrMarkedQuestions()
    }
    markedSave = () => {
        this.setState({
            markedSave: !this.state.markedSave
        })
    }
    allSave = () => {
        this.setState({
            allSave: !this.state.allSave
        })
    }
    refinishHandle = () => {
        const { data } = this.state;
        Modal.confirm({
            title: '提示',
            content: '您确定要重新作答吗？',
            onOk: () => {
                for (let i = 0; i < data.length; i++) {
                    const item = data[i];
                    item.is_audit = 0;
                }
                this.setState({
                    answers: [],
                    abc: 1,
                    currentQuestion: 0,
                    submited: false,
                    markedQuestions: [],
                    showSaveQuestionBank: false,
                    allWrongAnswers: [],//所有错题包含未答
                    allIds: [],//所有题
                    correctAnswers: [],//做对的没标记的题
                    rightAnswers: [],//做对的
                    markedSave: false,
                    allSave: false,
                    wrongAnswers: [],
                    checkboxValues: [],
                    data: [...data],
                    reFinish: true
                })
            }
        })

    }
    prevQuestion = () => {
        if (this.state.currentQuestion <= 0) return message.warn('已经是第一题了');
        this.setState({
            currentQuestion: this.state.currentQuestion - 1
        })
    }
    nextQuestion = () => {
        if (this.state.currentQuestion >= this.state.data.length - 1) return message.warn('已经是最后一题了');
        this.setState({
            currentQuestion: this.state.currentQuestion + 1
        })
    }
    componentDidMount() {
        stopActive('')
        document.body.style.background = "#f0f0f0"
        const { type, subject, p_type, wrongs } = this.props.match.params;
        const uid = localStorage.getItem('id') || '';
        if (!uid) {
            message.error('请先登录')
            this.props.history.push('/login')
            return
        }
        getTestPaper({ type, subject, p_type, uid, wrongs }).then(res => {
            if (!res[0]) {
                this.setState({
                    loading: false
                })
                if (res.status === '积分不够') return message.error('积分不足')
                return message.error('题库中没有题')
            }
            let answers = [];
            let checkboxValues = [];
            for (let i = 0; i < res.length; i++) {
                answers.push('')
                checkboxValues.push([])
            }
            this.setState({
                data: res,
                answers,
                loading: false,
                checkboxValues,
                startTime: new Date().getTime()
            })
        })
        if (localStorage.getItem('antd-pro-authority') === `["2"]`) {
            timer = setInterval(() => {
                const countTime = localStorage.getItem('countTime') || '';
                localStorage.setItem('countTime', String(Number(countTime) + 60))
                if (Number(countTime) >= 3600) {
                    clearInterval(timer)
                }
            }, 60000)
        }
    }
    componentWillUnmount() {
        clearTimeout(timer)
    }
    exitHandle = () => {
        // const {type,p_type,subject} = this.props.match.params;
        Modal.confirm({
            title: '提示',
            content: '确定退出练习？',
            onOk: () => {
                history.push(`/practice`)
            }
        })
    }
    render() {
        const { data, answers, currentQuestion, loading, submited, showSaveQuestionBank, allSave, markedSave, checkboxValues } = this.state;
        const { type, p_type } = this.props.match.params;
        const dataCurrentQuestion = data[currentQuestion] || {};
        const classnames = (is_audit: number) => {
            if (is_audit === 0) return 'question-order';
            if (is_audit === 2) return 'finshed';
            if (is_audit === 3) return 'marked';
        }
        const renderType = () => {
            if (type === '1') {
                return '单选题'
            }
            if (type === '2') {
                return '多选题'
            }
            if (type === '3') {
                return '判断题'
            }
        }
        const renderPType = () => {
            if (p_type === '1') {
                return '新题和错题'
            }
            if (p_type === '2') {
                return '新题'
            }
            if (p_type === '3') {
                return '错题'
            }
        }
        return (
            <div className={styles['test-paper-page']} style={{ padding: 25 }}>
                <Spin spinning={loading}>
                    <Row gutter={25}>
                        <Col span={5} >
                            <Card title={<div className={styles['practice-title']}>在线练习（{renderType()}）</div>}>
                                <Row gutter={10}>
                                    {data.map((item: any, index: number) => {
                                        return <Col span={4} key={item.id}>
                                            <div style={{ background: currentQuestion === index ? '#1890ff' : '' }}
                                                className={styles[classnames(item.is_audit)]}
                                                onClick={this.changeCurrentQuestion(item, index)}>{index + 1}</div>
                                        </Col>
                                    })}
                                </Row>
                                <Row gutter={10}>
                                    <Col span={6}><div className={styles['finshed-mark']}>已答</div></Col>
                                    <Col span={6}><div className={styles['not-finsh-mark']}>未答</div></Col>
                                    <Col span={6}><div className={styles['marked-mark']}>标记</div></Col>
                                </Row>
                            </Card>
                        </Col>
                        <Col span={19}>
                            <Card title={`${renderType()}（共${data.length || 100}道题，${renderPType()}）`} >
                                <div style={{ height: '80vh', overflow: 'auto' }}>
                                    <div key={dataCurrentQuestion.id} id={'question' + currentQuestion} className={styles['question-item']}>
                                        <div className={styles['question-top']}>
                                            <p className={styles['question-content']}> {currentQuestion + 1}.{dataCurrentQuestion.content}</p>
                                            <div style={{ float: 'right' }}>
                                                <Button type="primary" onClick={this.markThisQuestion(currentQuestion)} disabled={dataCurrentQuestion.is_audit === 3}>标记本题</Button><br />
                                                <Button style={{ marginTop: 25 }} onClick={this.checkAnswer(dataCurrentQuestion)}>查看答案</Button>
                                            </div>
                                        </div>
                                        {
                                            dataCurrentQuestion.img && <img src={fileurl + dataCurrentQuestion.img} onClick={() => window.open(fileurl + dataCurrentQuestion.img)} style={{ width: 400, cursor: 'pointer', marginBottom: 20 }} alt=" " />
                                        }
                                        {
                                            type === '1' && <div className={styles['single-select']}>
                                                <RadioGroup value={answers[currentQuestion]} onChange={this.changeAnswer(currentQuestion)}>
                                                    {dataCurrentQuestion.a && <div className={styles['single-select-item']}><Radio value="A">A. {dataCurrentQuestion.a}</Radio></div>}
                                                    {dataCurrentQuestion.b && <div className={styles['single-select-item']}><Radio value="B">B. {dataCurrentQuestion.b}</Radio></div>}
                                                    {dataCurrentQuestion.c && <div className={styles['single-select-item']}><Radio value="C">C. {dataCurrentQuestion.c}</Radio></div>}
                                                    {dataCurrentQuestion.d && <div className={styles['single-select-item']}><Radio value="D">D. {dataCurrentQuestion.d}</Radio></div>}
                                                    {dataCurrentQuestion.e && <div className={styles['single-select-item']}><Radio value="E">E. {dataCurrentQuestion.e}</Radio></div>}
                                                    {dataCurrentQuestion.f && <div className={styles['single-select-item']}><Radio value="F">F. {dataCurrentQuestion.f}</Radio></div>}
                                                </RadioGroup>
                                            </div>
                                        }
                                        {
                                            type === '2' && <div className={styles['single-select']}>
                                                <Checkbox.Group value={checkboxValues[currentQuestion]} onChange={(e) => this.changeBatchSelect(e, currentQuestion)}>
                                                    {dataCurrentQuestion.a && <div className={styles['single-select-item']}><Checkbox value="A">A. {dataCurrentQuestion.a}</Checkbox></div>}
                                                    {dataCurrentQuestion.b && <div className={styles['single-select-item']}><Checkbox value="B">B. {dataCurrentQuestion.b}</Checkbox></div>}
                                                    {dataCurrentQuestion.c && <div className={styles['single-select-item']}><Checkbox value="C">C. {dataCurrentQuestion.c}</Checkbox></div>}
                                                    {dataCurrentQuestion.d && <div className={styles['single-select-item']}><Checkbox value="D">D. {dataCurrentQuestion.d}</Checkbox></div>}
                                                    {dataCurrentQuestion.e && <div className={styles['single-select-item']}><Checkbox value="E">E. {dataCurrentQuestion.e}</Checkbox></div>}
                                                    {dataCurrentQuestion.f && <div className={styles['single-select-item']}><Checkbox value="F">F. {dataCurrentQuestion.f}</Checkbox></div>}
                                                </Checkbox.Group>
                                            </div>
                                        }
                                        {
                                            type === '3' && <div className={styles['single-select']}>
                                                <RadioGroup value={answers[currentQuestion]} onChange={this.changeAnswer(currentQuestion)}>
                                                    <div className={styles['single-select-item']}><Radio value="正确">正确</Radio></div>
                                                    <div className={styles['single-select-item']}><Radio value="错误">错误</Radio></div>
                                                </RadioGroup>
                                            </div>
                                        }

                                        {
                                            submited && <div className={styles['right-answer']}>
                                                <p>正确答案：{dataCurrentQuestion.answer}</p>
                                                {dataCurrentQuestion.answer_that && <p>解释说明：${dataCurrentQuestion.answer_that}</p>}
                                                {answers[currentQuestion] === String(dataCurrentQuestion.answer).trim() ? <p className={styles['correct']}>正确</p> : <p className={styles['error']}>错误</p>}
                                            </div>
                                        }

                                    </div>
                                    <Button type="primary" onClick={this.prevQuestion} style={{ marginRight: 20, marginTop: 20 }}>上一题</Button>
                                    <Button type="primary" onClick={this.nextQuestion} style={{ marginRight: 20, marginTop: 20 }}>下一题</Button>
                                </div>
                                <div style={{ width: 324, margin: 'auto', position: 'relative', top: 10 }}>
                                    {
                                        !submited && <Button type="primary" danger onClick={this.submitHandle}>交卷批改</Button>
                                    }
                                    {
                                        submited && <Button type="primary" danger onClick={this.showSaveQuestionBank}>存储题库</Button>
                                    }
                                    <Button type="primary" style={{ marginLeft: 30 }} onClick={this.refinishHandle}>重新作答</Button>
                                    <Button style={{ marginLeft: 30, backgroundColor: "#f60", borderColor: "#f60" }} onClick={this.exitHandle} danger type="primary">退出练习</Button>
                                </div>
                            </Card>
                        </Col>
                    </Row>
                </Spin>
                <Modal visible={showSaveQuestionBank} onCancel={this.hideSaveQuestionBank} title="存储题库" footer={[<Button type="primary" key="1" onClick={this.confirmSave}>确定</Button>]}>
                    <Row gutter={2}>
                        <Col span={12}> <Button style={{ marginTop: 15, backgroundColor: allSave ? '#f60' : '' }} onClick={this.allSave} type="primary">将已答错题存储到错题题题库</Button></Col>
                        <Col span={12}> <Button style={{ marginTop: 15, backgroundColor: markedSave ? '#f60' : '' }} onClick={this.markedSave} type="primary">将标记题存储到新题题库</Button></Col>
                        <p style={{ marginTop: 15 }}>您可以将试题归类到所在题库，便于针对下一次练习</p>
                    </Row>
                </Modal>
            </div>
        )
    }
}
